<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="即文本的高级匹配模式，提供搜索，替代等功能。其本质是一系列由特殊符号组成的字串，这个字串即正则表达式。由普通字符和特殊符号组成字符串，通过描述字符的重复和位置等行为，达到匹配某一类字符串的目的">
<meta name="keywords" content="Python,正则">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-正则（regex）">
<meta property="og:url" content="https://rencheng.cc/2019/08/12/python/正则/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="即文本的高级匹配模式，提供搜索，替代等功能。其本质是一系列由特殊符号组成的字串，这个字串即正则表达式。由普通字符和特殊符号组成字符串，通过描述字符的重复和位置等行为，达到匹配某一类字符串的目的">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-08-12T01:53:18.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-正则（regex）">
<meta name="twitter:description" content="即文本的高级匹配模式，提供搜索，替代等功能。其本质是一系列由特殊符号组成的字串，这个字串即正则表达式。由普通字符和特殊符号组成字符串，通过描述字符的重复和位置等行为，达到匹配某一类字符串的目的">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/08/12/python/正则/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Python-正则（regex） | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/08/12/python/正则/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Python-正则（regex）

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-08-12 09:53:18" itemprop="dateCreated datePublished" datetime="2019-08-12T09:53:18+08:00">2019-08-12</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">6.2k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>即文本的高级匹配模式，提供搜索，替代等功能。其本质是一系列由特殊符号组成的字串，这个字串即正则表达式。<br>由普通字符和特殊符号组成字符串，通过描述字符的重复和位置等行为，达到匹配某一类字符串的目的</p>
<a id="more"></a>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><h3 id="动机"><a href="#动机" class="headerlink" title="动机"></a>动机</h3><ol>
<li>文本处理已经成为计算机的常见工作之一</li>
<li>对文本内容的搜索，定位，提取是逻辑比较复杂的工作</li>
<li>为了快速解决上述问题，产生了正则表达式技术</li>
</ol>
<h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>即文本的高级匹配模式，提供搜索，替代等功能。其本质是一系列由特殊符号组成的字串，这个字串即正则表达式。</p>
<h3 id="匹配原理"><a href="#匹配原理" class="headerlink" title="匹配原理"></a>匹配原理</h3><p>由普通字符和特殊符号组成字符串，通过描述字符的重复和位置等行为，达到匹配某一类字符串的目的</p>
<h3 id="目标"><a href="#目标" class="headerlink" title="目标"></a>目标</h3><ol>
<li>熟练掌握正则表达式符号</li>
<li>实现基本的文本搜索，定位，提取，理解正则用法</li>
<li>能够适用re模块操作正则表达式</li>
</ol>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ul>
<li>方便文本处理</li>
<li>支持语言众多</li>
<li>使用灵活多样</li>
</ul>
<h2 id="基础实践"><a href="#基础实践" class="headerlink" title="基础实践"></a>基础实践</h2><h3 id="re模块简单实用"><a href="#re模块简单实用" class="headerlink" title="re模块简单实用"></a>re模块简单实用</h3><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">re.findall(pattern, <span class="built_in">string</span>)</span><br></pre></td></tr></table></figure>
<p>功能: 使用正则表达式匹配目标字符串内容<br>参数</p>
<ul>
<li>pattern  正则表达式</li>
<li>string   目标字符串<br>返回值： 列表，列表中为匹配到的内容</li>
</ul>
<h3 id="元字符的使用"><a href="#元字符的使用" class="headerlink" title="元字符的使用"></a>元字符的使用</h3><h4 id="普通字符"><a href="#普通字符" class="headerlink" title="普通字符"></a>普通字符</h4><p><strong>元字符</strong> ： <code>a</code>  <code>b</code>   <code>c</code><br><strong>匹配规则</strong>： 每个字符匹配对应的字符</p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"hello"</span>,<span class="string">"hello world"</span>)</span><br><span class="line">[<span class="string">'hello'</span>]</span><br></pre></td></tr></table></figure>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"你好"</span>,<span class="string">"你好北京"</span>)</span><br><span class="line">[<span class="string">'你好'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="或"><a href="#或" class="headerlink" title="或"></a>或</h4><p><strong>元字符</strong>：  <code>|</code><br><strong>匹配规则</strong>： 匹配 | 两边任意一个正则表达式</p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"ab|cd"</span>,<span class="string">"abcdefghialkjasbab"</span>)</span><br><span class="line">[<span class="string">'ab'</span>, <span class="string">'cd'</span>, <span class="string">'ab'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配单个字符"><a href="#匹配单个字符" class="headerlink" title="匹配单个字符"></a>匹配单个字符</h4><p><strong>元字符</strong>：  <code>.</code><br><strong>匹配规则</strong>： 匹配除换行外的任意字符<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">f</span><span class="selector-class">.o</span> <span class="selector-tag">--</span>&gt; <span class="selector-tag">foo</span>  <span class="selector-tag">fao</span>  <span class="selector-tag">f</span>@<span class="keyword">o</span>  f o</span><br></pre></td></tr></table></figure></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"f.o"</span>,<span class="string">"foo is not fao"</span>)</span><br><span class="line">[<span class="string">'foo'</span>, <span class="string">'fao'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配开始位置"><a href="#匹配开始位置" class="headerlink" title="匹配开始位置"></a>匹配开始位置</h4><p><strong>元字符</strong> ： <code>^</code><br><strong>匹配规则</strong>：匹配目标字符串的开头位置</p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"^Tom"</span>,<span class="string">"Tom is a boy"</span>)</span><br><span class="line">[<span class="string">'Tom'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配结束位置"><a href="#匹配结束位置" class="headerlink" title="匹配结束位置"></a>匹配结束位置</h4><p><strong>元字符</strong> ： <code>$</code><br><strong>匹配规则</strong> ： 匹配字符串的结束位置</p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"Tom$"</span>,<span class="string">"hi Tom"</span>)</span><br><span class="line">[<span class="string">'Tom'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配重复"><a href="#匹配重复" class="headerlink" title="匹配重复 *"></a>匹配重复 *</h4><p><strong>元字符</strong> ： <code>*</code><br><strong>匹配规则</strong>： 匹配前面的字符出现0次或多次<br><figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fo</span>*  --&gt; fooooooooo  <span class="keyword">f</span>  <span class="keyword">fo</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"fo*"</span>,<span class="string">"fadsfafoooafo"</span>)</span><br><span class="line">[<span class="string">'f'</span>, <span class="string">'f'</span>, <span class="string">'fooo'</span>, <span class="string">'fo'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配重复-1"><a href="#匹配重复-1" class="headerlink" title="匹配重复 +"></a>匹配重复 +</h4><p><strong>元字符</strong> ： <code>+</code><br><strong>匹配规则</strong>： 匹配前面的字符出现1次或多次<br><figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fo</span>+  --&gt; <span class="keyword">fo</span>   fooooo</span><br></pre></td></tr></table></figure></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"fo+"</span>,<span class="string">"fadsfafoooafo"</span>)</span><br><span class="line">[<span class="string">'fooo'</span>, <span class="string">'fo'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配重复-？"><a href="#匹配重复-？" class="headerlink" title="匹配重复 ？"></a>匹配重复 ？</h4><p><strong>元字符</strong> ： <code>?</code><br><strong>匹配规则</strong>： 匹配前面的字符出现0次或1次<br><figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">fo</span>? --&gt;  <span class="keyword">f</span>   <span class="keyword">fo</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"fo?"</span>,<span class="string">"fasdffoafooooo"</span>)</span><br><span class="line">[<span class="string">'f'</span>, <span class="string">'f'</span>, <span class="string">'fo'</span>, <span class="string">'fo'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配重复-n"><a href="#匹配重复-n" class="headerlink" title="匹配重复 {n}"></a>匹配重复 {n}</h4><p><strong>元字符</strong> ： <code>{n}</code><br><strong>匹配规则</strong>： 匹配指定的重复次数<br><figure class="highlight xl"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">fo</span>&#123;3&#125;  --&gt;</span> fooo</span><br></pre></td></tr></table></figure></p>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"fo&#123;2&#125;"</span>,<span class="string">"fasdffoafooooo"</span>)</span><br><span class="line">[<span class="string">'foo'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配重复-m-n"><a href="#匹配重复-m-n" class="headerlink" title="匹配重复 {m,n}"></a>匹配重复 {m,n}</h4><p><strong>元字符</strong> ： <code>{m,n}</code><br><strong>匹配规则</strong> ： 匹配前面的正则表达式 m—n次</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fo&#123;<span class="number">2</span>,<span class="number">4</span>&#125; --&gt; foo  fooo  foooo</span><br></pre></td></tr></table></figure>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"fo&#123;2,4&#125;"</span>,<span class="string">"fasdfofoooafooooo"</span>)</span><br><span class="line">[<span class="string">'fooo'</span>, <span class="string">'foooo'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配字符集合"><a href="#匹配字符集合" class="headerlink" title="匹配字符集合"></a>匹配字符集合</h4><p><strong>元字符</strong>： <code>[字符集]</code><br><strong>匹配规则</strong> ： 匹配任意一个字符集中的字符</p>
<figure class="highlight accesslog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">[abc123]</span>   a  b  c  <span class="number">1</span>  <span class="number">2</span>  <span class="number">3</span> </span><br><span class="line"><span class="string">[a-z]</span>  </span><br><span class="line"><span class="string">[A-Z]</span></span><br><span class="line"><span class="string">[0-9]</span></span><br><span class="line"><span class="string">[_123a-z]</span></span><br></pre></td></tr></table></figure>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall("^[<span class="string">A-Z</span>][<span class="symbol">a-z</span>]*","Boy")</span><br><span class="line">['Boy']</span><br></pre></td></tr></table></figure>
<h4 id="匹配字符集"><a href="#匹配字符集" class="headerlink" title="匹配字符集"></a>匹配字符集</h4><p><strong>元字符</strong> ： <code>[^...]</code><br><strong>匹配规则</strong> ：字符集取非，除列出的字符之外任意一个字符</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[^abc] --&gt; 除<span class="selector-tag">a</span> <span class="selector-tag">b</span> c之外任意字符</span><br></pre></td></tr></table></figure>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"[^ ]+"</span>,<span class="string">"a little boy"</span>)</span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'little'</span>, <span class="string">'boy'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配任意（非）数字字符"><a href="#匹配任意（非）数字字符" class="headerlink" title="匹配任意（非）数字字符"></a>匹配任意（非）数字字符</h4><p><strong>元字符</strong> ： <code>\d</code>  <code>\D</code><br><strong>匹配规则</strong>：</p>
<ul>
<li><code>\d</code> 匹配任意数字字符     <code>[0-9]</code></li>
<li><code>\D</code> 匹配任意非数字字符   <code>[^0-9]</code></li>
</ul>
<figure class="highlight 1c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">"1\d&#123;10&#125;"</span>,<span class="string">"18888886666"</span>)</span><br><span class="line">['<span class="number">1888888666</span>6']</span><br></pre></td></tr></table></figure>
<h4 id="匹配任意（非）普通字符"><a href="#匹配任意（非）普通字符" class="headerlink" title="匹配任意（非）普通字符"></a>匹配任意（非）普通字符</h4><p><strong>元字符</strong> ： <code>\w</code>   <code>\W</code><br><strong>匹配规则</strong>: </p>
<ul>
<li><code>\w</code> 普通字符  <code>[_0-9a-zA-Z]</code> 也能匹配普通汉字</li>
<li><code>\W</code> 非普通字符</li>
</ul>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">re</span><span class="selector-class">.findall</span>("\<span class="selector-tag">w</span>+","<span class="selector-tag">hello</span><span class="selector-id">#nihao</span>%<span class="selector-tag">asdf</span>@<span class="keyword">adsgdfg</span>!<span class="keyword">df</span>&amp;")</span><br><span class="line">['<span class="keyword">hello</span>', <span class="string">'nihao'</span>, <span class="string">'asdf'</span>, <span class="string">'adsgdfg'</span>, <span class="string">'df'</span>]</span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">re</span><span class="selector-class">.findall</span>("\<span class="selector-tag">W</span>+","<span class="selector-tag">hello</span><span class="selector-id">#nihao</span>%<span class="selector-tag">asdf</span>@<span class="keyword">adsgdfg</span>!<span class="keyword">df</span>&amp;")</span><br><span class="line">['#', <span class="string">'%'</span>, <span class="string">'@'</span>, <span class="string">'!'</span>, <span class="string">'&amp;'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="匹配任意（非）空字符"><a href="#匹配任意（非）空字符" class="headerlink" title="匹配任意（非）空字符"></a>匹配任意（非）空字符</h4><p><strong>元字符</strong> ： </p>
<ul>
<li><code>\s</code>  匹配任意空字符  <code>[ \r\t\n\v\f]</code></li>
<li><code>\S</code>  匹配任意非空字符</li>
</ul>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"\w+\s+\w+"</span>,<span class="string">"hello   world"</span>)</span><br><span class="line">[<span class="string">'hello   world'</span>]</span><br></pre></td></tr></table></figure>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.<span class="keyword">findall</span>(<span class="string">"\S+"</span>,<span class="string">"hello this is tom"</span>)</span><br><span class="line">[<span class="string">'hello'</span>, <span class="string">'this'</span>, <span class="string">'is'</span>, <span class="string">'tom'</span>]</span><br></pre></td></tr></table></figure>
<blockquote>
<p>空格也属于空字符</p>
</blockquote>
<h4 id="匹配字符串位置"><a href="#匹配字符串位置" class="headerlink" title="匹配字符串位置"></a>匹配字符串位置</h4><p><strong>元字符</strong> ： <code>\A</code>   <code>\Z</code><br><strong>匹配规则</strong>：  </p>
<ul>
<li><code>\A</code> 匹配字符串开头位置  <code>^</code></li>
<li><code>\Z</code> 匹配字符串结尾位置  <code>$</code> </li>
</ul>
<p>绝对匹配 ： 正则表达式要完全匹配目标字符串内容</p>
<p>在正则表达式开始和结束位置加上<code>^</code> <code>$</code> (或者<code>\A</code> <code>\Z</code>)。这样正则表达式必须匹配整个目标字符串才会有结果<br><figure class="highlight 1c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">"\A\d+\Z"</span>,<span class="string">"123445"</span>)</span><br><span class="line">['<span class="number">123445</span>']</span><br></pre></td></tr></table></figure></p>
<h4 id="匹配（非）单词边界"><a href="#匹配（非）单词边界" class="headerlink" title="匹配（非）单词边界"></a>匹配（非）单词边界</h4><p><strong>元字符</strong> ： <code>\b</code>   <code>\B</code><br><strong>匹配规则</strong> ： </p>
<ul>
<li><code>\b</code> 匹配单词边界位置 普通字符和非普通字符交界认为是单词边界</li>
<li><code>\B</code> 匹配非单词边界位置</li>
</ul>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">r"num\b"</span>,<span class="string">"num#asdf#"</span>)</span><br><span class="line">[<span class="string">'num'</span>]</span><br></pre></td></tr></table></figure>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">r"num\b"</span>,<span class="string">"numasdf#"</span>)</span><br><span class="line">[]</span><br></pre></td></tr></table></figure>
<h4 id="元字符总结"><a href="#元字符总结" class="headerlink" title="元字符总结"></a>元字符总结</h4><p>匹配单个字符 ： <code>a</code>   <code>.</code>   <code>\d</code>  <code>\D</code>  <code>\w</code>  <code>\W</code>  <code>\s</code>  <code>\S</code> <code>[...]</code>  <code>[^...]</code></p>
<p>匹配重复 ： <code>*</code>   <code>+</code> <code>?</code>  <code>{n}</code>  <code>{m,n}</code></p>
<p>匹配位置 ： <code>^</code>  <code>$</code>  <code>\A</code>  <code>\Z</code>  <code>\b</code>  <code>\B</code> </p>
<p>其他 ： <code>|</code>  <code>()</code>  <code>\</code></p>
<p>正则表达式转义</p>
<p>正则中的特殊符号：</p>
<p><code>.</code>  <code>*</code>  <code>+</code>  <code>?</code>  <code>^</code>  <code>$</code>  <code>[]</code>  <code>{}</code> <code>()</code>  <code>|</code> <code>\</code></p>
<p>正则表达式如果匹配特殊字符需要加 <code>\</code> 表达转义</p>
<figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">	 正则          目标字符串</span><br><span class="line">e.g.    \<span class="variable">$\</span>d+  ----&gt;    <span class="variable">$10</span></span><br></pre></td></tr></table></figure>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">         pattern        string</span><br><span class="line">python  <span class="string">"\\$\\d+"</span>       <span class="string">"<span class="variable">$10</span>"</span> </span><br><span class="line"></span><br><span class="line">raw     r<span class="string">"\$\d+"</span>       <span class="string">"<span class="variable">$10</span>"</span></span><br></pre></td></tr></table></figure>
<p>raw字串 ： 原始字符串对内容不解释转义，就表达内容原            本意义</p>
<h3 id="贪婪与非贪婪"><a href="#贪婪与非贪婪" class="headerlink" title="贪婪与非贪婪"></a>贪婪与非贪婪</h3><p><strong>贪婪模式</strong> ： 正则表达式的重复匹配总是尽可能多的向后匹配更多内容</p>
<p><code>*</code>   <code>+</code>   <code>?</code>  <code>{m,n}</code></p>
<p><strong>非贪婪（懒惰模式）</strong> ： 尽可能少的匹配内容</p>
<p>贪婪 —-&gt; 非贪婪  <code>*?</code>  <code>+?</code>  <code>??</code>  <code>{m,n}?</code><br><figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">r"ab+?"</span>,<span class="string">"abbbbbbbb"</span>)</span><br><span class="line">[<span class="string">'ab'</span>]</span><br></pre></td></tr></table></figure></p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.findall(<span class="string">r"ab??"</span>,<span class="string">"abbbbbbbb"</span>)</span><br><span class="line">[<span class="string">'a'</span>]</span><br></pre></td></tr></table></figure>
<h4 id="正则表达式的子组"><a href="#正则表达式的子组" class="headerlink" title="正则表达式的子组"></a>正则表达式的子组</h4><p>可以使用<code>()</code>为正则表达式建立子组，子组可以看做是正则表达式内部操作的一个整体</p>
<blockquote>
<p>子组是在正则表达式整体匹配到内容的前提下才会发挥作用，它不影响正则表达式整体去匹配目标内容这一原则</p>
</blockquote>
<h5 id="子组使用"><a href="#子组使用" class="headerlink" title="子组使用"></a>子组使用</h5><ol>
<li>作为内部整体可以改变某些元字符的行为</li>
</ol>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.search(<span class="string">r"(ab)+\d+"</span>,<span class="string">"ababab1234"</span>).group()</span><br><span class="line"><span class="string">'ababab1234'</span></span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.search(<span class="string">r"\w+@\w+\.(com|cn)"</span>,<span class="string">"abc@123.com"</span>).group()</span><br><span class="line"><span class="string">'abc@123.com'</span></span><br></pre></td></tr></table></figure>
<ol>
<li>子组在某些操作中可以单独提取出匹配内容</li>
</ol>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">re.search(<span class="string">r"(https|http|ftp)://\S+"</span>,<span class="string">"https://www.baidu.com"</span>).group(<span class="number">1</span>)</span><br><span class="line"><span class="string">'https'</span></span><br></pre></td></tr></table></figure>
<h5 id="子组使用注意事项"><a href="#子组使用注意事项" class="headerlink" title="子组使用注意事项"></a>子组使用注意事项</h5><ul>
<li>一个正则表达式中可以有多个子组</li>
<li>子组一般由外到内，由左到右称之为第一，第二 第三。。。。子组</li>
<li>子组不能重叠，嵌套也不宜很多</li>
</ul>
<blockquote>
<p>search 只能匹配一个结果</p>
</blockquote>
<h4 id="捕获组-和-非捕获组"><a href="#捕获组-和-非捕获组" class="headerlink" title="捕获组 和 非捕获组"></a>捕获组 和 非捕获组</h4><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">格式 ： （?P&lt;<span class="built_in">name</span>&gt;pattern）</span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">e.g.</span><br><span class="line">re.search(<span class="string">r"(?P&lt;dog&gt;ab)cdef"</span>,<span class="string">'abcdefghti'</span>).group(<span class="string">'dog'</span>)</span><br><span class="line">Out[<span class="number">130</span>]: <span class="string">'ab'</span></span><br></pre></td></tr></table></figure>
<p>作用 ： 可以通过组名更方便获取某组内容</p>
<h3 id="正则表达式设计原则"><a href="#正则表达式设计原则" class="headerlink" title="正则表达式设计原则"></a>正则表达式设计原则</h3><ol>
<li>正确性 ，能正确匹配到目标内容</li>
<li>排他性 ，除了要匹配的内容，尽可能不会匹配与到其他内容</li>
<li>全面性 ，需要对目标的各种情况进行考虑，做到不遗漏</li>
</ol>
<h2 id="re模块"><a href="#re模块" class="headerlink" title="re模块"></a>re模块</h2><h3 id="compile"><a href="#compile" class="headerlink" title="compile"></a>compile</h3><p>用来生成正则表达式对象</p>
<p><strong>regex = compile(pattern,flags=0)</strong></p>
<ul>
<li>功能 ： 生成正则表达式对象</li>
<li>参数 ： <ul>
<li>pattern  正则表达式</li>
<li>flags  功能标志位，丰富正则表达式的匹配功能</li>
</ul>
</li>
<li>返回值 : 返回正则表达式对象</li>
</ul>
<h3 id="findall"><a href="#findall" class="headerlink" title="findall"></a>findall</h3><h4 id="re模块调用"><a href="#re模块调用" class="headerlink" title="re模块调用"></a>re模块调用</h4><p><strong>re.findall(pattern,string,flags)</strong></p>
<ul>
<li>功能 ：从目标字符串查找正则匹配内容</li>
<li>参数 ： <ul>
<li>pattern  正则表达式</li>
<li>string  目标字符串</li>
<li>flags  标志位</li>
</ul>
</li>
<li>返回值 ： 返回匹配到的内容 如果正则有子组则只返回子组对应内容</li>
</ul>
<h4 id="正则对象调用"><a href="#正则对象调用" class="headerlink" title="正则对象调用"></a>正则对象调用</h4><p><strong>regex.findall(string,pos,endpos)</strong></p>
<ul>
<li>功能 ：从目标字符串查找正则匹配内容</li>
<li>参数 ： <ul>
<li>string  目标字符串</li>
<li>pos  匹配目标的起始位置</li>
<li>endpos  匹配目标的终止位置</li>
</ul>
</li>
<li>返回值 ： 返回匹配到的内容 如果正则有子组则只返回子组对应内容</li>
</ul>
<h3 id="split"><a href="#split" class="headerlink" title="split"></a>split</h3><p>正则表达式所匹配的内容，做字符串的切割<br><strong>re.split(pattern,string,flags = 0)</strong></p>
<ul>
<li>功能：根据正则匹配内容切割字符串</li>
<li>参数： pattern  string  flags</li>
<li>返回值： 返回列表，列表中为切割的内容</li>
</ul>
<h3 id="sub"><a href="#sub" class="headerlink" title="sub"></a>sub</h3><p>使用一个字符串去替换目标字符串被正则表达式匹配到的内容<br><strong>re.sub(pattern,replaceStr,string,max,flags)</strong></p>
<ul>
<li>功能： 替换正则匹配到的目标子串部分</li>
<li>参数： <ul>
<li>pattern</li>
<li>replaceStr ： 要替换的内容</li>
<li>string </li>
<li>max   最多替换几处 默认全部替换</li>
<li>flags</li>
</ul>
</li>
<li>返回值 ： 返回替换后的字符串</li>
</ul>
<h3 id="subn"><a href="#subn" class="headerlink" title="subn"></a>subn</h3><p>使用一个字符串去替换目标字符串被正则表达式匹配到的内容<br><strong>re.subn(pattern,replaceStr,string,max,flags)</strong></p>
<ul>
<li>功能： 替换正则匹配到的目标子串部分</li>
<li>参数： <ul>
<li>pattern</li>
<li>replaceStr ： 要替换的内容</li>
<li>string </li>
<li>max   最多替换几处 默认全部替换</li>
<li>flags</li>
</ul>
</li>
<li>返回值 ： 返回一个元组，为实际替换了几处和替换后的字符串</li>
</ul>
<blockquote>
<p>sub 和 subn区别</p>
<ul>
<li>sub返回替换后的字符串</li>
<li>subn返回替换了几处</li>
</ul>
</blockquote>
<h3 id="finditer"><a href="#finditer" class="headerlink" title="finditer"></a>finditer</h3><p>相比findall返回一个迭代对象<br><strong>re.finditer(pattern,string,flags)</strong></p>
<ul>
<li>功能： 使用正则表达式匹配目标字符串</li>
<li>参数： pattern  string flags</li>
<li>返回值： 返回一个迭代对象，迭代到的内容是一个<em>match</em>对象</li>
</ul>
<h3 id="fullmatch"><a href="#fullmatch" class="headerlink" title="fullmatch"></a>fullmatch</h3><p>相当于在最前面写一个<code>^</code>，最后面写一个<code>$</code>， 只匹配到一处，返回一个match对象<br><strong>fullmatch(pattern,string,flags)</strong></p>
<ul>
<li>功能： 完全匹配目标字符串</li>
<li>参数： pattern,string,flags</li>
<li>返回值：返回匹配到的match对象 如果没匹配成功返回None</li>
</ul>
<h3 id="match"><a href="#match" class="headerlink" title="match"></a>match</h3><p>相当于只匹配到开头，返回一个match对象<br><strong>match(pattern,string,flags)</strong></p>
<ul>
<li>功能： 从开头位置匹配目标字符串</li>
<li>参数： pattern,string,flags</li>
<li>返回值：返回匹配到的match对象 如果没匹配成功返回None</li>
</ul>
<h3 id="search"><a href="#search" class="headerlink" title="search"></a>search</h3><p><strong>search(pattern,string,flags)</strong></p>
<ul>
<li>功能： 正则表达式匹配目标字符串，<strong>只匹配第一处</strong></li>
<li>参数： pattern,string,flags</li>
<li>返回值：返回匹配到的match对象 如果没匹配成功返回None</li>
</ul>
<p>compile对象属性：</p>
<p>flags  ： 标志位<br>pattern ： 正则表达式<br>groups： 有多少子组<br>groupindex ： 捕获组形成组名和序列号的字典<br>              组名为键，第几组为值</p>
<h3 id="match对象属性"><a href="#match对象属性" class="headerlink" title="match对象属性"></a>match对象属性</h3><h4 id="属性变量"><a href="#属性变量" class="headerlink" title="属性变量"></a>属性变量</h4><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">pos     匹配目标字符串的开始位置</span><br><span class="line">endpos  匹配目标字符串的结束位置</span><br><span class="line">re      正则表达式</span><br><span class="line"><span class="built_in">string</span>  目标字符串</span><br><span class="line">lastgroup  最后一组的组名</span><br><span class="line">lastindex  最后一组是第几组</span><br></pre></td></tr></table></figure>
<h4 id="属性方法"><a href="#属性方法" class="headerlink" title="属性方法"></a>属性方法</h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">span</span><span class="params">()</span></span>  匹配内容的开始位置</span><br><span class="line"><span class="function"><span class="title">start</span><span class="params">()</span></span> 匹配内容的结束位置</span><br><span class="line"><span class="function"><span class="title">end</span><span class="params">()</span></span>   匹配内容的起止位置</span><br></pre></td></tr></table></figure>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">group</span><span class="params">()</span></span></span><br><span class="line">功能 ： 获取match对象对应的内容</span><br><span class="line">参数 ： 默认为<span class="number">0</span> 表示获取整个正则匹配的内容</span><br><span class="line">        如果为序列号或者子组名则为获取某个子组匹配的对应内容</span><br><span class="line">返回值：返回得到的子串</span><br></pre></td></tr></table></figure>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">groupdict</span><span class="params">()</span></span>  获取捕获组名作为键，对应内容作为值的字典</span><br><span class="line"><span class="function"><span class="title">groups</span><span class="params">()</span></span>   获取每个子组匹配内容</span><br></pre></td></tr></table></figure>
<h3 id="flags-参数的使用"><a href="#flags-参数的使用" class="headerlink" title="flags  参数的使用"></a>flags  参数的使用</h3><p>re.compile  re.findall  re.search  re.match<br>re.finditer  re.fullmatch  re.sub  re.subn  re.split<br>上面这些方法都有flags参数<br>作用： 辅助正则表达式，丰富匹配结果<br><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">I</span> ==  IGNORECASE  匹配时忽略字母的大小写</span><br><span class="line"><span class="attr">S</span> ==  DOTALL     作用于元字符 . 使其可以匹配换行 </span><br><span class="line"><span class="attr">M</span> ==  MULTILINE  作用于^  $  使其可以匹配每一行开头结尾位置</span><br><span class="line"><span class="attr">X</span> ==  VERBOSE    可以给正则添加注释</span><br></pre></td></tr></table></figure></p>
<p>使用多个标志位使用按位或连接<br><figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">e.g.</span><br><span class="line">flags = re.X | re.I</span><br></pre></td></tr></table></figure></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/正则/" rel="tag"># 正则</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/12/mongodb/聚合操作/" rel="next" title="MongoDB-聚合操作">
                <i class="fa fa-chevron-left"></i> MongoDB-聚合操作
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/22/python/tqdm/" rel="prev" title="Python-tqdm">
                Python-tqdm <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#动机"><span class="nav-number">1.1.</span> <span class="nav-text">动机</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">1.2.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#匹配原理"><span class="nav-number">1.3.</span> <span class="nav-text">匹配原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#目标"><span class="nav-number">1.4.</span> <span class="nav-text">目标</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特点"><span class="nav-number">1.5.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础实践"><span class="nav-number">2.</span> <span class="nav-text">基础实践</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#re模块简单实用"><span class="nav-number">2.1.</span> <span class="nav-text">re模块简单实用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#元字符的使用"><span class="nav-number">2.2.</span> <span class="nav-text">元字符的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#普通字符"><span class="nav-number">2.2.1.</span> <span class="nav-text">普通字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#或"><span class="nav-number">2.2.2.</span> <span class="nav-text">或</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配单个字符"><span class="nav-number">2.2.3.</span> <span class="nav-text">匹配单个字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配开始位置"><span class="nav-number">2.2.4.</span> <span class="nav-text">匹配开始位置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配结束位置"><span class="nav-number">2.2.5.</span> <span class="nav-text">匹配结束位置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配重复"><span class="nav-number">2.2.6.</span> <span class="nav-text">匹配重复 *</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配重复-1"><span class="nav-number">2.2.7.</span> <span class="nav-text">匹配重复 +</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配重复-？"><span class="nav-number">2.2.8.</span> <span class="nav-text">匹配重复 ？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配重复-n"><span class="nav-number">2.2.9.</span> <span class="nav-text">匹配重复 {n}</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配重复-m-n"><span class="nav-number">2.2.10.</span> <span class="nav-text">匹配重复 {m,n}</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配字符集合"><span class="nav-number">2.2.11.</span> <span class="nav-text">匹配字符集合</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配字符集"><span class="nav-number">2.2.12.</span> <span class="nav-text">匹配字符集</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配任意（非）数字字符"><span class="nav-number">2.2.13.</span> <span class="nav-text">匹配任意（非）数字字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配任意（非）普通字符"><span class="nav-number">2.2.14.</span> <span class="nav-text">匹配任意（非）普通字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配任意（非）空字符"><span class="nav-number">2.2.15.</span> <span class="nav-text">匹配任意（非）空字符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配字符串位置"><span class="nav-number">2.2.16.</span> <span class="nav-text">匹配字符串位置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匹配（非）单词边界"><span class="nav-number">2.2.17.</span> <span class="nav-text">匹配（非）单词边界</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#元字符总结"><span class="nav-number">2.2.18.</span> <span class="nav-text">元字符总结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#贪婪与非贪婪"><span class="nav-number">2.3.</span> <span class="nav-text">贪婪与非贪婪</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#正则表达式的子组"><span class="nav-number">2.3.1.</span> <span class="nav-text">正则表达式的子组</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#子组使用"><span class="nav-number">2.3.1.1.</span> <span class="nav-text">子组使用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#子组使用注意事项"><span class="nav-number">2.3.1.2.</span> <span class="nav-text">子组使用注意事项</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#捕获组-和-非捕获组"><span class="nav-number">2.3.2.</span> <span class="nav-text">捕获组 和 非捕获组</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#正则表达式设计原则"><span class="nav-number">2.4.</span> <span class="nav-text">正则表达式设计原则</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#re模块"><span class="nav-number">3.</span> <span class="nav-text">re模块</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#compile"><span class="nav-number">3.1.</span> <span class="nav-text">compile</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#findall"><span class="nav-number">3.2.</span> <span class="nav-text">findall</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#re模块调用"><span class="nav-number">3.2.1.</span> <span class="nav-text">re模块调用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#正则对象调用"><span class="nav-number">3.2.2.</span> <span class="nav-text">正则对象调用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#split"><span class="nav-number">3.3.</span> <span class="nav-text">split</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sub"><span class="nav-number">3.4.</span> <span class="nav-text">sub</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#subn"><span class="nav-number">3.5.</span> <span class="nav-text">subn</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#finditer"><span class="nav-number">3.6.</span> <span class="nav-text">finditer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fullmatch"><span class="nav-number">3.7.</span> <span class="nav-text">fullmatch</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#match"><span class="nav-number">3.8.</span> <span class="nav-text">match</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#search"><span class="nav-number">3.9.</span> <span class="nav-text">search</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#match对象属性"><span class="nav-number">3.10.</span> <span class="nav-text">match对象属性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#属性变量"><span class="nav-number">3.10.1.</span> <span class="nav-text">属性变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#属性方法"><span class="nav-number">3.10.2.</span> <span class="nav-text">属性方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#flags-参数的使用"><span class="nav-number">3.11.</span> <span class="nav-text">flags  参数的使用</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
